package com.danciyixue.boot.dcyx.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.danciyixue.boot.dcyx.mapper.SemesterMapper;
import com.danciyixue.boot.dcyx.service.SemesterService;
import com.danciyixue.boot.dcyx.model.entity.Semester;
import com.danciyixue.boot.dcyx.model.form.SemesterForm;
import com.danciyixue.boot.dcyx.model.query.SemesterQuery;
import com.danciyixue.boot.dcyx.model.vo.SemesterVO;
import com.danciyixue.boot.dcyx.converter.SemesterConverter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 学期信息服务实现类
 *
 * @author youlaitech
 * @since 2025-06-15 16:25
 */
@Service
@DS("dcyx")
@RequiredArgsConstructor
public class SemesterServiceImpl extends ServiceImpl<SemesterMapper, Semester> implements SemesterService {

    private final SemesterConverter semesterConverter;

    /**
    * 获取学期信息分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<SemesterVO>} 学期信息分页列表
    */
    @Override
    public IPage<SemesterVO> getSemesterPage(SemesterQuery queryParams) {
        Page<SemesterVO> pageVO = this.baseMapper.getSemesterPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取学期信息表单数据
     *
     * @param id 学期信息ID
     * @return 学期信息表单数据
     */
    @Override
    public SemesterForm getSemesterFormData(Long id) {
        Semester entity = this.getById(id);
        return semesterConverter.toForm(entity);
    }
    
    /**
     * 新增学期信息
     *
     * @param formData 学期信息表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveSemester(SemesterForm formData) {
        Semester entity = semesterConverter.toEntity(formData);
        return this.save(entity);
    }
    
    /**
     * 更新学期信息
     *
     * @param id   学期信息ID
     * @param formData 学期信息表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateSemester(Long id,SemesterForm formData) {
        Semester entity = semesterConverter.toEntity(formData);
        return this.updateById(entity);
    }
    
    /**
     * 删除学期信息
     *
     * @param ids 学期信息ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteSemesters(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的学期信息数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

}
